import pexpect

class LogFileWrapper:
    def __init__(self, file):
        self.file = file

    def write(self, data):
        if isinstance(data, bytes):
            data = data.decode('utf-8')  # 假设使用 UTF-8 编码进行解码
        self.file.write(data)

    def close(self):
        self.file.close()

    def flush(self):
        self.file.flush()


class BluetoothSpeaker:
    def __enter__(self):
        self.logfile = open('bluetoothctl.log', 'w')
        self.wrapped_logfile = LogFileWrapper(self.logfile)
        self.speaker = pexpect.spawn('bluetoothctl', logfile=self.wrapped_logfile)
        self.speaker.expect('bluetooth')
        self.initial_config()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.wrapped_logfile.close()
        self.speaker.terminate()

    def initial_config(self):
        self.speaker.sendline('power on')
        self.speaker.expect(['Changing', 'power', 'on','succeeded'])

        self.speaker.sendline('agent on')
        self.speaker.expect(['Agent', 'is', 'already', 'Agent','registered'])

        self.speaker.sendline('default-agent')
        self.speaker.expect(['Default', "agent", "request", "successful"])

        self.speaker.sendline('pairable on')
        self.speaker.expect(['Changing', 'pairable', 'on','succeeded'])

        self.speaker.sendline('discoverable on')
        self.speaker.expect(['Changing', 'discoverable', 'on','succeeded'])


if __name__ == '__main__':
    with BluetoothSpeaker() as speaker:
        print('初始化蓝牙音箱完成')